package com.fable.web.controller.file;

import com.fable.biz.operate.CustomerService;
import com.fable.biz.operate.FileRecordService;
import com.fable.common.constant.FableConstant;
import com.fable.common.utils.JsonResult;
import com.fable.dal.dto.AdminUserDTO;
import com.fable.dal.model.AdminUserDO;
import com.fable.dal.model.FileRecordDO;
import com.fable.utils.QiniuImgUtil;
import com.fable.utils.StringUtil;
import com.fable.web.common.admin.UserTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * Created by weishuai on 18/5/28.
 */
@Controller
@RequestMapping(value = "/upload")
public class FileController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    FileRecordService fileRecordService;


    @RequestMapping(value = "/upload.json", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult add(HttpServletRequest request, ModelMap model, @RequestParam(value = "fileselect", required = true) MultipartFile[] files) {
        JsonResult json = new JsonResult();
        AdminUserDTO adminUserDTO= UserTools.getAdminUser(request.getSession());
        if (adminUserDTO == null) {
            json.setErrMsg("对象不存在!");
            return json;
        }

        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        StringBuffer fileIds = new StringBuffer();

        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file.isEmpty()) {
                    continue;
                }
                try {
                    long size = file.getSize();
                    String uuid = UUID.randomUUID().toString();
                    FileRecordDO recordDO = new FileRecordDO();
                    recordDO.setUserName(adminUserDTO.getNick());
                    recordDO.setFileSize(size);
                    recordDO.setFileToken(uuid);
                    recordDO.setFileName(file.getOriginalFilename());
                    recordDO.setUserId(adminUserDTO.getId());
                    Date date = new Date();
                    recordDO.setGmtCreate(date);
                    recordDO.setGmtModified(date);
                    fileRecordService.add(recordDO);
                    Long fileId = recordDO.getId();
                    String key = QiniuImgUtil.upload(adminUserDTO.getNick(), file.getBytes(), uuid);
                    if (StringUtil.isNotBlank(key)) {
                        fileIds.append(fileId).append(",");
                    } else {
                        json.setErrMsg("上传七牛云失败");
                        logger.error("上传七牛云失败,userName:{},fileName:{},key:{}", adminUserDTO.getNick(), file.getOriginalFilename(),key);
                    }
                } catch (IOException e) {
                    json.setErrMsg("上传失败");
                    logger.error("提交出错，文件操作异常,userName:{},fileName:{}", file.getOriginalFilename(), e);
                }

            }

        }


        json.setData(fileIds);

        return json;

    }
}
